package com.base.servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class FileDownloadServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	/**
	 * 
	 */
	private static Logger logger = LoggerFactory.getLogger(FileDownloadServlet.class);
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		// 必须调用，否则IE出现的三个选择中的“打开”会提示找不到文件
		resp.reset();
		resp.setContentType("text/html;charset=UTF-8");
		req.setCharacterEncoding("UTF-8");
		ServletContext ctx = getServletContext();
		String filePath = ctx.getRealPath("/") + req.getParameter("filePath");
		InputStream is = new FileInputStream(new File(filePath));
//		resp.setHeader("Content-Disposition", "attachment; filename=" + req.getParameter("fileName"));
		OutputStream output = null;
		try {
			output = resp.getOutputStream();
			byte[] b = new byte[1024];
			int i = 0;

			while ((i = is.read(b)) > 0) {
				output.write(b, 0, i);
			}
			output.flush();
		} catch (IOException e) {
			logger.error("download file error:" + e.getMessage());
		} finally {
			try {
				if (is != null) {
					is.close();
					is = null;
				}
				if (output != null) {
					output.close();
					output = null;
				}
			} catch (IOException e) {
				logger.error("close outputstream error:" + e.getMessage());
			}
		}
	}

	@Override
	public void init() throws ServletException {
		// TODO Auto-generated method stub
	}
}
